import './App.css';
import React, { useState } from 'react';
import { message,Image,Spin,FloatButton,Popconfirm,Steps} from 'antd';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import { request,request_baseURL } from '@/utils/index'

function App() {
  
  const [selectedFile, setSelectedFile] = useState(null);
  const [processedImages, setProcessedImages] = useState([]);
  const [imageUploaded, setImageUploaded] = useState(false);
  // base image
  const [previewUrl, setPreviewUrl] = useState(null);
  // color image
  const [colorImagewUrl, setColorImagewUrl] = useState(null);
  // mix image
  const [mixImagewUrl, setMixImagewUrl] = useState(null);
// mix images
  const [mixImages,setMixImages] = useState([])
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [showing, setShowing] = useState(false);
  const [uploadFileId, setUploadFileId] = useState(0);
  // 加载框
  const [spinning, setSpinning] = useState(false);
  const [tip, setTip] = useState('');

  // 全局提示框
  const [messageApi, contextHolder] = message.useMessage();

  // current
  const [current,setCurrent] = useState(0)
  
  // 成功提示
  const successUpload = () => {
    messageApi.open({
      type: 'success',
      content: 'Upload Success',
      duration:1
    });
  };

  const successProcess = () => {
    messageApi.open({
      type: 'success',
      content: 'Process Success',
      duration:1
    });
  };

  const successShowImage = () => {
    messageApi.open({
      type: 'success',
      content: 'ShowImage Success',
      duration:1
    });
  };
  

  const handleFileChange = (e) => {
    setColorImagewUrl(null)
    setMixImagewUrl(null)
    setProcessedImages([])
    setImageUploaded(false)
    setUploadSuccess(false)
    setShowing(false)
    const file = e.target.files[0];
    setSelectedFile(file);
    const reader = new FileReader();
    reader.onload = () => {
      setPreviewUrl(reader.result);
    };
    reader.readAsDataURL(file);
  };

  const handleUpload = async () => {
    setTip('Upload...')
    setSpinning(true)
    const formData = new FormData();
    formData.append('image', selectedFile);

    try {
      let response = await request.post(`/upload_image/`, formData);
      setUploadFileId(response.data.time)
      console.log(response.data.time);
      setImageUploaded(true);
      setUploadSuccess(true);
    } catch (error) {
      messageApi.open({
        type: 'error',
        content: 'Error uploading image:', error,
      });
      console.error('Error uploading image:', error);
      setSpinning(false)
      return
    }
    setSpinning(false)
    setProcessing(true);
    successUpload();
    setCurrent(1);
  };

  const handleProcessImage = async () => {
    setTip('Processing...')
    setSpinning(true)

    // number
    console.log(uploadFileId);
    try {
      const userString = uploadFileId; // 整数参数值
      const url = `/process_image/?user_string=${userString}&base_image_name=${selectedFile.name}`;

      const response = await request.post(url);
      console.log(response.data);
  } catch (error) {
    messageApi.open({
      type: 'error',
      content: 'Processed timeout!!!!'+ error,
    });
      console.error('请求出错:', error);
      setSpinning(false)
      return
  }

  try {
    const userString = uploadFileId; // 整数参数值
    const url = `/mix_together/?user_string=${userString}&base_image_name=${selectedFile.name}`;

    const response = await request.post(url);

    console.log(response.data);
} catch (error) {
    console.error('请求出错:', error);
}
    setShowing(true);
    setSpinning(false)
    setMixImagewUrl(`${request_baseURL}/colorinput/${uploadFileId}/blended_image.png`)
    setColorImagewUrl(`${request_baseURL}/colorinput/${uploadFileId}/${uploadFileId}/color/color.png`)
    setProcessing(false);
    successProcess();
    setCurrent(2);
  };

  const handleShowImage = async () => {
    setTip('ShowImageing...')
    setSpinning(true)
    console.log(uploadFileId);
    try {
      const userString = uploadFileId; // 整数参数值
      const url = `/list_images/?user_string=${userString}`;

      const response = await request.get(url);

      console.log(response.data);
      setProcessedImages([...response.data])
  } catch (error) {
      console.error('请求出错:', error);
  }
// mix images name & url
  try {
    const userString = uploadFileId; // 整数参数值
    const url = `/mix_images/?user_string=${userString}&base_image_name=${selectedFile.name}`;

    const response = await request.post(url);

    console.log(response.data);
    let tempMixImageUrl = response.data
    for(let i = 0;i < response.data.length;i++){
      tempMixImageUrl[i] = `${request_baseURL}/colorinput/${uploadFileId}/output_mixfolder/${tempMixImageUrl[i]}`
    }
    console.log(tempMixImageUrl);
    setMixImages([...tempMixImageUrl])
} catch (error) {
    console.error('请求出错:', error);
}
    setShowing(false);
    successShowImage();
    setSpinning(false)
    setCurrent(3);
  };
  
  const confirm = async () => {
    // console.log(e);
    if(processedImages.length == 0){
      messageApi.open({
        type: 'error',
        content: 'Processed Image is null',
      });
      return
    }
    const zip = new JSZip();
  // 图片文件列表
  const imageFiles = [`${request_baseURL}/colorinput/${uploadFileId}/blended_image.png`,`${request_baseURL}/colorinput/${uploadFileId}/${uploadFileId}/color/color.png`,`${request_baseURL}/colorinput/${uploadFileId}/${selectedFile.name}`,...processedImages,...mixImages];

  // 遍历图片文件列表，将每个图片文件添加到压缩包中
  for (let i = 0; i < imageFiles.length; i++) {
    console.log(imageFiles[i]);
    const response = await fetch(imageFiles[i]);
    const blob = await response.blob();
    
    // 获取图片文件名称（不含路径）
    const fileName = imageFiles[i].split('/').pop();
    
    zip.file(fileName, blob);
  }
  // 生成压缩包
  const content = await zip.generateAsync({ type: "blob" });
  // 下载压缩包
  saveAs(content, `${selectedFile.name}.zip`);

  message.success('uploading zip...');
  };
  const cancel = () => {
    // console.log(e);
    message.error('Cancel download');
  };
  // css变量
  const buttonStyle = {
    position: 'absolute',
    bottom: '0', // 设置距离底部位置
    right: '0',  // 设置距离右侧位置
  };
  return (
    <div className="app">
      <Spin tip={tip} spinning={spinning}>
      
    
    {contextHolder}
      <div className="container">
      <Steps
    size="small"
    current={current}
    items={[
      {
        title: 'Upload',
      },
      {
        title: 'In Progress',
      },
      {
        title: 'Show layer Image',
      },
    ]}
  />
        <h2>Image Upload and Processing</h2>
        <div className="custom-file-input">
          <input type="file" onChange={handleFileChange} />
          <label>Choose File</label>
        </div>
        <div className="grid-container">
        <Image.PreviewGroup
              preview={{
                onChange: (current, prev) => console.log(`current index: ${current}, prev index: ${prev}`),
              }}
            >
              
              {previewUrl && <div className="grid-item"><Image src={previewUrl} alt="Selected" width={150} /></div>}
              {colorImagewUrl && <div className="grid-item"><Image src={colorImagewUrl} alt="Selected" width={150} className="grid-item"/></div>}
              {mixImagewUrl && <div className="grid-item"><Image src={mixImagewUrl} alt="Selected" width={150} className="grid-item"/></div>}
              {/* <Image width={150} src={image}/> */}
              </Image.PreviewGroup>
        </div>
        <button onClick={handleUpload} disabled={imageUploaded} className="upload-button">
          {'Upload'}
        </button>

        {/* {uploadSuccess && <p className="success-message">Image uploaded successfully!</p>} */}

        {processedImages.length > 0 && (
          <div className="processed-images">
            <h3>Processed Images:</h3>
            <div className="grid-container">
            <Image.PreviewGroup
              preview={{
                onChange: (current, prev) => console.log(`current index: ${current}, prev index: ${prev}`),
              }}
            >
              {mixImages.map((image, index) => (
                <div key={index} className="grid-item">
                  <Image width={150} src={image}/>
                  {/* <img src={image} alt={`Processed ${index + 1}`} className="processed-image" /> */}
                </div>
              ))}
              </Image.PreviewGroup>
            </div>
          </div>
        )}

        <button onClick={handleProcessImage} disabled={!processing} className="process-button">
          {'Process Image'}
        </button>

        <button onClick={handleShowImage} disabled={!showing} className="show-button">
          {'Show layer Image'}
        </button>
        <Popconfirm
    title="Download compressed package"
    description="Are you sure you want to download the compressed package?"
    onConfirm={confirm}
    onCancel={cancel}
    okText="Yes"
    cancelText="No"
  >
    <FloatButton tooltip={<div>Download zip</div>} style={buttonStyle}/>
  </Popconfirm>
      </div>
      </Spin>
    </div>
  );
}

export default App;
